package com.web.helper.calculation;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.web.helper.Caculate;
import io.github.coho04.githubapi.Github;
import io.github.coho04.githubapi.entities.GHUser;
import io.github.coho04.githubapi.entities.repositories.GHRepository;

import java.time.OffsetDateTime;
import java.util.List;

import static com.common.constant.Token.GITHUB_TOKEN;

/**
 * 一年内commit数量
 */

public class CaculateCommits implements Caculate {

    public int process(String username) {
        Github g = new Github(GITHUB_TOKEN);
        GHUser user = g.findUserByName(username);

        List<GHRepository> repos = user.listRepositories();
        System.out.println(repos.size());
        int totalCommit = 0;

        for(GHRepository repo : repos){

            OffsetDateTime updatedAt = repo.getUpdatedAt();
            System.out.println(updatedAt);
            //更新时间在一年前跳过
            if(updatedAt.isBefore(OffsetDateTime.now().minusYears(1))){
                continue;
            }

            //获取仓库commit清单
            String originalUrl = repo.getCommitsUrl();
            // 替换仓库名称并去除尾部的 "{/sha}"
            String formattedUrl = originalUrl.replace("{/sha}", "")
                    + "?per_page=100";
            System.out.println(repo.getCommitsUrl() + "   " + formattedUrl);

            // 获取用户的所有事件
            String eventsResponse = HttpUtil.get(formattedUrl);
            JSONArray commitsArray = null;

            try {
                // 尝试将响应解析为 JSONArray
                commitsArray = JSON.parseArray(eventsResponse);
            } catch (JSONException e) {
                // 如果发生异常，说明不是数组，尝试解析为 JSONObject,是无用信息不做处理
                continue;
            }

            if(commitsArray == null){
                continue;
            }

            int commitSum = 0;

            // 遍历每条提交记录
            for (int i = 0; i < commitsArray.size(); i++) {
                JSONObject commitObject = commitsArray.getJSONObject(i);

                // 获取 "commit:author:date" 的值
                String authorDate = commitObject.getJSONObject("commit")
                        .getJSONObject("author")
                        .getString("date");

                //一年前的不要
                if(OffsetDateTime.parse(authorDate).isBefore(OffsetDateTime.now().minusYears(1))){
                    continue;
                }

                // 获取 "committer:login" 的值
                JSONObject committerLogin = commitObject.getJSONObject("committer");
                if(committerLogin == null){
                    continue;
                }
                String login =  committerLogin.getString("login");

                //非开发者者自己的不要
                if(!committerLogin.equals(username)){
                    continue;
                }

                commitSum++;
                System.out.println("Commit Author Date: " + authorDate);
                System.out.println("Committer Login: " + committerLogin);

            }
            System.out.println(repo.getName() + "的commits : " + commitSum);
            totalCommit += commitSum;
        }

        System.out.println("totalCommit: " + totalCommit);

        return totalCommit;
    }
}
